package com.ztgf.order.service;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.commodity.models.bo.CategoryImportSaveBO;
import com.ztgf.commodity.models.vo.CategoryBrandVO;
import com.ztgf.dubbo.exception.ServiceException;
import com.ztgf.order.models.vo.DealOrderInfoVO;
import com.ztgf.common.utils.CustomizeUtil;
import com.ztgf.order.common.config.YmlConfig;
import com.ztgf.order.mapper.DealOrderInfoMapper;
import com.ztgf.order.models.bo.*;
import com.ztgf.order.models.dto.*;
import com.ztgf.order.models.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.ztgf.commodity.models.enums.CategoryImportUtil.*;
import static com.ztgf.commodity.models.enums.CategoryImportUtil.LABEL_ATTRIBUTES;
import static com.ztgf.order.models.enums.DealOrderImportUtil.*;

/**
 * 订单表控制器
 *
 * @author chenyu.wang
 * @Date 2020-06-03 15:32:26
 */
@Slf4j
@DubboService
@Lazy
public class DealOrderInfoServiceImpl extends ServiceImpl<DealOrderInfoMapper, DealOrderInfoDTO> implements IDealOrderInfoService {

    @Resource
    private YmlConfig ymlConfig;


    @Override
    public boolean add(DealOrderInfoBO DealOrderInfoSaveBO) {
        DealOrderInfoDTO dto = new DealOrderInfoDTO();
        BeanUtils.copyProperties(DealOrderInfoSaveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    @Override
    public boolean importDealOrder(byte[] input) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 解析excel
        // 将文件byte转成inputStream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(input);
        try {
            Workbook workbook = WorkbookFactory.create(inputStream);
            inputStream.close();
            // 获取工作表对象
            Sheet sheet = workbook.getSheetAt(0);
            // 获取Excel表格中数据的行数
            int totalRow = sheet.getPhysicalNumberOfRows();
            // 获取Excel表格中数据的列数
            int totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
            // 第一行
            Row oneRow = sheet.getRow(0);
            // 整个表格的数据
            List<DealOrderInfoBO> list = new ArrayList<>();
            for (int i = 1; i <= totalRow; i++) {
                // 行
                Row row = sheet.getRow(i);
                // 若有空行继续下一行（因为EXCEL有空行时报错故加上此代码）
                if (null == row || "".equals(row)) {
                    totalRow--;
                    continue;
                }
                String check = this.getCellValue(row.getCell(0));
                if (CustomizeUtil.strIsNull(check)) {
                    totalRow--;
                    continue;
                }
                // 一行的数据
                DealOrderInfoBO rowObject = new DealOrderInfoBO();
                for (int j = 0; j <= totalCells; j++) {
                    // 获取标题
                    String title = this.getCellValue(oneRow.getCell(j)).trim();
                    // 获取单元格值
                    String value = this.getCellValue(row.getCell(j)).trim();
                    if (CustomizeUtil.strIsNotNull(value)) {
                        switch (title) {
                            case SELLER_NAME:
                                rowObject.setSellerName(value);
                                break;
                            case COMPANY_NAME:
                                rowObject.setCompanyName(value);
                                break;
                            case ACTUAL_MONEY:
                                rowObject.setActualMoney(new BigDecimal(String.valueOf(value)).setScale(2, RoundingMode.HALF_UP));
                                break;
                            case CREATE_TIME:
                                rowObject.setCreateTime(sdf.parse(value));
                                break;
                            case CONTACT_ID:
                                rowObject.setContactId(value);
                                break;
                            default:
                                break;
                        }
                    }
                }
                list.add(rowObject);
            }
            // TODO 处理解析后的数据
            if(list != null && list.size() > 0){
                for(int i=0;i<list.size();i++){
                    DealOrderInfoBO saveBo = list.get(i);
                    try{
                        this.add(saveBo);
                    }catch (Exception e){
                        if(i == list.size() - 1){
                            break;
                        }
                        continue;
                    }
                }
                return true;
            }
            return false;
        } catch (Exception e) {
            log.info("导入属性的错误信息:{}", e.getMessage());
            e.printStackTrace();
        }
        return false;
    }


    private String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                cellValue = cell.getStringCellValue().trim();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                DecimalFormat df = new DecimalFormat("0");

                cellValue = df.format(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA:
                cellValue = cell.getCellFormula();
                break;
            default:
                cellValue = "";
        }
        return cellValue;
    }
}
